export class Ws {
    ws;
    protocol;

    onopen;
    onmessage;
    onerror;
    onclose;

    constructor({
        onopen,
        onmessage,
        onerror,
        onclose
    }, protocol) {
        this.protocol = protocol;
        this.onopen = onopen;
        this.onmessage = onmessage;
        this.onerror = onerror;
        this.onclose = onclose;
    }

    get readyState () {
        return this.ws ? this.ws.readyState : null
    }
    get bufferedAmount () {
        return this.ws ? this.ws.bufferedAmount : null
    }

    create(url, protocol) {
        if("WebSocket" in window) {
            this.ws = new WebSocket(url, protocol)
            this.ws.onopen = this.handleOpen
            this.ws.onmessage = this.handleMessage
            this.ws.onmerror = this.handleError
            this.ws.onclose = this.handleClose
            return this
        } else {
            throw Error('Does not support WebSocket!')
        }
    }

    static handleOpen(e) {
        console.log('successfully');
        if(typeof this.onopen === 'function') 
            this.onopen(e);
    }
    static handleMessage(res) {
        console.log('message', res);
        if(typeof this.onmessage === 'function') 
            this.onmessage(res);
    }
    static handleError(err) {
        console.log('error', err);
        if(typeof this.onerror === 'function') 
            this.onerror(err);
    }
    static handleClose(e) {
        console.log('close');
        if(typeof this.onclose === 'function') 
            this.onclose(e);
    }

    send(params) {
        if(this.ws)
            this.ws.send(params);
    }

    close() {
        if(this.ws) 
            this.ws.close()
    }

    destroy() {
        if(this.ws) 
            this.ws.close()
            this.ws = null;
    }
    
}